/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef } from 'react';
import { Button, Popconfirm, Space, message } from 'antd';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ProFormInstance } from '@ant-design/pro-form';
import { useQjDpColumns, formatReqData } from '@/components/_pages/Finance/dbTransfer/_utils';
import KbDbTransferModal from '@/components/_pages/Finance/dbTransfer/KbExportModal';
import { useRequest } from 'umi';
import { getQueryConfig as qj_getQueryConfig } from '@/services/tools/qjOrder';
import styles from './index.less';
import { checkIsMobile } from '@base/utils';
import {
  qj_createExportTask as createExportTask,
  qj_exportTaskLists as exportTaskLists,
  qj_getOrderList as getOrderList,
} from '@/services/Finance/dbRransfer';

const QJDpTable = () => {
  const { data: queryConfig } = useRequest(qj_getQueryConfig);
  const { columns } = useQjDpColumns({ queryConfig });
  const [isOpened, updateIsOpened] = useState<boolean>(false);
  const formRef = useRef<ProFormInstance>();

  const handleOpen = () => updateIsOpened(true);

  const handleExport = () => {
    formRef.current?.validateFields().then((values) => {
      const reqData = formatReqData(values);
      createExportTask(reqData).then(({ code, msg }) => {
        if (code == 0) {
          message.success('添加下载任务成功！快去任务列表查看吧');
        } else {
          message.error(msg);
        }
      });
    });
  };

  const getTableList = (values: any) => {
    const reqData = formatReqData(values);
    return getOrderList(reqData).then((res) => {
      const { code, data, msg } = res;
      if (code == 0) {
        return {
          data: data.list,
          total: data.total,
        };
      } else {
        message.error(msg);
        return {
          data: [],
        };
      }
    });
  };

  const isMobile = checkIsMobile();
  return (
    <div className={styles.dbTransFer}>
      <DragTable>
        <ProTable
          rowKey='id'
          columns={columns}
          formRef={formRef}
          scroll={{ x: 1700 }}
          options={false}
          request={getTableList}
          toolBarRender={() => [
            <Space key={'action'} direction={isMobile ? 'vertical' : 'horizontal'}>
              <Popconfirm key='export' title='你确定导出对账单？' onConfirm={handleExport}>
                <Button type='primary'>导出对账单</Button>
              </Popconfirm>
              <Button key='open' type='primary' onClick={handleOpen}>
                查看导出列表
              </Button>
            </Space>,
          ]}
          search={{
            collapsed: false,
            collapseRender: false,
          }}
        />
      </DragTable>
      <KbDbTransferModal
        requestList={exportTaskLists}
        isOpened={isOpened}
        updateIsOpened={updateIsOpened}
      />
    </div>
  );
};

export default QJDpTable;
